package com.example.damaimaven.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.damaimaven.entity.Cart;
import com.example.damaimaven.entity.Orderitem;
import com.example.damaimaven.entity.Orders;
import com.example.damaimaven.entity.Product;
import com.example.damaimaven.mapper.CartMapper;
import com.example.damaimaven.mapper.OrderitemMapper;
import com.example.damaimaven.mapper.OrdersMapper;
import com.example.damaimaven.mapper.ProductMapper;
import com.example.damaimaven.service.BizException;
import com.example.damaimaven.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zzh
 * @since 2024-07-09
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    OrderitemMapper orderitemMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    CartMapper cartMapper;
    @Override
    @Transactional //开启事务
    public void commit(Orders orders) throws BizException {
        //字段验证
        if (orders.getItems() == null || orders.getItems().isEmpty()) {
            throw new BizException("订单必须包含商品!");
        }
        for (Orderitem orderitem : orders.getItems()) {
            if(orderitem.getCount()<=0){
                throw new BizException("商品数量必须大于0!!");
            }
        }
        if(orders.getAddr() == null || orders.getAddr().isBlank()){
            throw  new BizException("请填写收货地址!");
        }
        if(orders.getPhone() == null || orders.getPhone().isBlank()){
            throw  new BizException("请填写收货电话!");
        }
        if(orders.getName() == null || orders.getName().isBlank()){
            throw  new BizException("请填写收货人姓名!");
        }

        //设置订单时间
        orders.setOrdertime(LocalDateTime.now());
        //1表示已支付
        orders.setState(1);
        //先存主表
        save(orders);//mybatis 再新增主表记录的同时，会返回数据库生成的主键值Oid
        //再存子(从)表
        //统计总金额
        double sum = 0;
        for (Orderitem orderitem : orders.getItems()) {
            Product product = productMapper.selectById(orderitem.getPid());
            orderitem.setSubtotal(product.getShopPrice() * orderitem.getCount());
            sum += orderitem.getSubtotal();
            //设置从表的关联的主键
            orderitem.setOid(orders.getOid());
            orderitemMapper.insert(orderitem);
            // TODO 清空购物车
            LambdaQueryWrapper<Cart> lqw = new LambdaQueryWrapper<Cart>();
            lqw.eq(Cart::getUid, orders.getUid());
            lqw.eq(Cart::getPid, orderitem.getPid());
            cartMapper.delete(lqw);
        }
        orders.setTotal(sum);

        //更新订单总金额
        updateById(orders);

    }
}
